function [  ] = changeDetection( varargin )
% A function for image differcing.

% basePic(the base picture) and chanPic(the warp picture) must be pre-processed.
% You can provide their path as basePicPath and chanPicPath.
if (nargin == 2)
    basePicPath = varargin{1};
    chanPicPath = varargin{2};
    detectMethod = 'Otsu';
elseif (nargin == 3)
    basePicPath = varargin{1};
    chanPicPath = varargin{2};
    detectMethod = varargin{3};
else
    fprintf('The number of input is wrong!\n');
    return
end

[basePic, ] = loadEnviData(basePicPath);
[chanPic, ] = loadEnviData(chanPicPath);

diffPic = chanPic - basePic;
[h, w, d] = size(diffPic);
diffPic = reshape(diffPic, [h * w, d]);
mag = sqrt(sum(diffPic.^2, 2));

figure(1)
hist(mag, 100);

if (strcmp(detectMethod, 'Otsu') == 1),
    otsuMode(mag, [h, w]);
elseif (strcmp(detectMethod, 'Manual') == 1),
    manualMode(mag, [h, w]);
else
    fprintf('You can separate CHANGED with NON-CHANGED using as ''Otsu'' or ''Manual''.\n');
    return
end

end

function otsuMode(mag, magSize)
% Otsu method.
    h = magSize(1);
    w = magSize(2);
    
    maxMag = max(mag);
    minMag = min(mag);
    mag = uint8(floor((mag-minMag)/(maxMag-minMag)*255));

    thres = graythresh(mag);
    
    mag = reshape(mag, [h, w]);
    cd = im2bw(mag, thres);
    figure(2)
    imshow(cd);
end

function manualMode(mag, magSize)
% Manual choose.
    h = magSize(1);
    w = magSize(2);
    
    maxMag = max(mag);
    minMag = min(mag);
    thres = -1;
    while (thres > maxMag || thres < minMag),
        [thres, ~] = ginput(1);
    end
    fprintf('You choose %g as the threshold.\n', thres);
    thres = (thres - minMag) / (maxMag-minMag);
    mag = uint8(floor((mag-minMag)/(maxMag-minMag)*255));
    
    mag = reshape(mag, [h, w]);
    cd = im2bw(mag, thres);
    figure(2)
    imshow(cd);
end